﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using popLib;
using System.Collections;
using PhotoMgr.src.common;
using PhotoMgr.src.database;

namespace PhotoMgr.src.gui.category
{
    public partial class SettingDetaill : Form
    {
        #region Variable
        public bool NhanDoi { get; set; }

        public bool ThemMoi { get; set; }

        public int ID { get; set; }

        public int IDNhanDoi { get; set; }

        public bool inDGV { get; set; }

        public Setting Record { get; set; }

        public FormAction Action { get; set; }

        public FormValidation FormValidator { get; set; }

        public bool UpdateMode { get; set; }

        public bool IsDatabaseChanged { get; set; }

        public string FormTitle { get; set; }
        #endregion

        #region Contructor
        public SettingDetaill(FormAction action, object id)
        {
            InitializeComponent();

            Action = action;

            ID = NumberLib.getInt(id);

            UpdateMode = true;

            this.Icon = PhotoMgr.Properties.Resources.logo32;
        }

        public SettingDetaill(FormAction action, int id)
        {
            InitializeComponent();

            Action = action;

            ID = id;

            UpdateMode = true;

            this.Icon = PhotoMgr.Properties.Resources.logo32;
        }

        public SettingDetaill(FormAction action)
        {
            InitializeComponent();

            Action = action;

            UpdateMode = false;

            this.Icon = PhotoMgr.Properties.Resources.logo32;
        }
        #endregion

        #region Event Functions
        private void UserDetail_Load(object sender, EventArgs e)
        {
            FormLoad();
        }
        private void btn_add_Click(object sender, EventArgs e)
        {
            ButtonAdd();
        }

        private void btn_update_Click(object sender, EventArgs e)
        {
            ButtonUpdate();
        }

        private void btn_dispose_Click(object sender, EventArgs e)
        {
            ButtonDispose();
        }

        private void btn_confirm_Click(object sender, EventArgs e)
        {
            ButtonConfirm();
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            ButtonSave();
        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            ButtonCancel();
        }

        private void btn_print_Click(object sender, EventArgs e)
        {
            ButtonPrint();
        }

        private void ToaThuoc_Detail_FormClosing(object sender, FormClosingEventArgs e)
        {
            FormClose(e);
        }

        private void btn_copy_Click(object sender, EventArgs e)
        {
            ButtonCopy();
        }

        public virtual void FormClose(FormClosingEventArgs e)
        {
            if (FormValidator.CurrentFormState != FormValidation.FormState.Ready)
            {
                if (!Global.FormMessage(Global.FormMessageType.ConfirmCancel, "Nhập Liệu Lương Căn Bản ").Success)
                {
                    e.Cancel = true;
                    return;
                }
            }
        }
        #endregion

        #region Handle Functions
        enum BHXHEnum { STT, MaNhanVien, HoVaTen, SoXoBHXH, SoXoBHYT, NgaySinh, GioiTinh, SoCMND, NgayCap, MaTinhCap, NguyenQuan, ChucDanhCongViec, DiaChi, NoiKCB_Tinh, NoiKCB_BV, GhiChu };

        public virtual void FormLoad()
        {
            //init default value here
            FormTitle = "Thông tin chi tiết thiết lập";
            FormLib.UpdateControlTabIndex(gbx_cotainer.Controls);

            //init default data
            Global.InitStatusCombobox(TinhTrang, Global.StatusType.Status, false);

            //DBManager.Fill....
            InitFormValidation();
            ViewDetail();

            UpdateFormAction();
            FillData();

            if (NhanDoi)
            {
                ButtonCopy(IDNhanDoi);
            }

            if (ThemMoi)
            {
                ThemMoi = false;
            }

            ThayDoiKichThuoc();
        }

        public void ExecuteViewDetail(object ID)
        {
            if (FormValidator.CurrentFormState == FormValidation.FormState.Ready)
            {
                this.ID = NumberLib.getInt(ID);

                UpdateMode = true;

                ViewDetail();

                UpdateFormAction();
            }
            else
            {
                FormLib.alert("Bạn đang cập nhật/thêm mới thông tin!!\r\nXin vui lòng hoàn tất trước khi xem chứng từ khác.", "Thông báo");
            }
        }

        public virtual void ButtonUpdate()
        {
            FormValidator.ChangeState(FormValidation.FormState.UpdateCurrent);
        }

        public virtual void ButtonDispose() {
            ReturnSet rs = Global.FormMessage(Global.FormMessageType.ConfirmDispose, new string[] { "thông tin lương căn bản", txMaxScore.Text });
            if (rs.Success)
            {
                LyDoHuy.Text = rs.Message;
                NguoiHuy.Text = UserAccount.Instance.Username;
                //NgayHuy.Values = Global.GetServerDateTime();

                string currentTinhTrang = TinhTrang.SelectedValue.ToString();

                TinhTrang.SelectedValue = "H";

                ButtonSave();

                if (FormValidator.IsFormValidated)
                {
                    ViewDetail();

                    UpdateFormAction();
                }
                else
                {
                    TinhTrang.SelectedValue = currentTinhTrang;
                }
            }
        }

        public virtual void ButtonAdd()
        {
            //change mode and hide all buttons
            btn_update.Visible = false;
            btn_add.Visible = false;
            btn_dispose.Visible = false;
            btn_confirm.Visible = true;
            UpdateMode = false;

            Record = new Setting();

            Record.Status = "A";
            TinhTrang.SelectedValue = "A";

            FormValidator.ChangeState(FormValidation.FormState.CreateNew);
        }

        public virtual void ButtonConfirm() 
        {
            if (Global.FormMessage(Global.FormMessageType.ConfirmAccept, new string[] { "Thông tin báo cáo ", txMaxScore.Text }).Success)
            {
                TinhTrang.SelectedValue = "XN";

                ButtonSave();

                ViewDetail();

                UpdateFormAction();
            }
        }

        public virtual void ButtonCancel()
        {
            if (UpdateMode)
            {
                FillData();
                FormValidator.ChangeState(FormValidation.FormState.Ready);
            }
            else
            {
                this.Close();
            }
        }

        public virtual void ButtonCopy(int IDnhandoi)
        {
            ////change mode and hide all buttons
            //btn_update.Visible = false;
            //btn_copy.Visible = false;
            ////btn_add.Visible = false;
            //btn_dispose.Visible = false;
            //btn_confirm.Visible = true;

            //UpdateMode = false;

            //int ID_tam = IDnhandoi;
            //FormValidator.ChangeState(FormValidation.FormState.CreateNew);

            ////set default value in form
            //BienPhi itemTam = DBManager.Detail_BienPhi(ID_tam);

            //TenNguoiDung.Text = itemTam.TenDichVu;
            //NgayCapNhat.Text = itemTam.NgayCapNhat.Value.ToString();

            //String tinhtranghientai = TinhTrang.SelectedValue.ToString();
            //if (tinhtranghientai == "H")
            //{
            //    gbx_cotainer.Height = 210;
            //}

            //Record = new LuongCanBan();

            //Record.TinhTrang = "M";
            //TinhTrang.SelectedValue = "M";
        }

        public virtual void ButtonCopy()
        {
            ////change mode and hide all buttons
            //btn_update.Visible = false;
            //btn_copy.Visible = false;
            ////btn_add.Visible = false;
            //btn_dispose.Visible = false;
            //btn_confirm.Visible = true;
            //UpdateMode = false;
            ////Record = new KhungGiaBHYT();

            //int ID_tam = this.ID;
            //FormValidator.ChangeState(FormValidation.FormState.CreateNew);

            ////set default value in form
            //var itemTam = DBManager.Detail_BienPhi(ID);

            //TenNguoiDung.Text = "";
            //NgayCapNhat.Values = Global.GetServerDateTime();
            //TenNguoiDung.Text = itemTam.TenDichVu;
            //NguoiCapNhat.Text = UserAccount.Instance.Username;

            //String tinhtranghientai = TinhTrang.SelectedValue.ToString();

            //if (tinhtranghientai == "H")
            //{
            //    gbx_cotainer.Height = 112;
            //}

            //Record = new LuongCanBan();

            //Record.TinhTrang = "M";
            //TinhTrang.SelectedValue = "M";
        }

        private bool IsDuplicateRecord()
        {
            ReturnSet rs = DBManager.CheckExistedSetting(txSettingName.Text);
            if (rs.Success)
            {
                FormLib.alert("Thông tin về thiết lập này đã được tạo từ ]!!\r\nXin vui lòng xóa thiết lập cũ trước khi tạo thiết lập mới.", "Thông báo");
                return true;
            }
            return false;
        }

        public virtual void ButtonSave()
        {

            if (!StringLib.isValid(txMaxScore.Text))
            {
                MessageBox.Show("Giá trị thiết không hợp lệ !!");
                return;
            }

            if (!FormValidator.Validate())
            {
                MessageBox.Show("Thông tin nhập không hợp lệ !!");
                return;
            }

            if (!UpdateMode && IsDuplicateRecord())
            {
                MessageBox.Show("Dữ liệu không hợp lệ !!");
                return;
            }

            Setting current = new Setting();

            current.SettingID = Record.SettingID;
            current.SettingName = Global.GetString(txSettingName.Text);
            current.MaxScore = txMaxScore.Text;
            current.AllowDecimalScore = AloowDecimal.Checked;
            current.DelayTime = NumberLib.getInt(txDelayTime.Value);

            current.Status = TinhTrang.SelectedValue.ToString();

            //Set Up
            ReturnSet rs = DBManager.Save_Setting(UpdateMode, current, Record);

            if (rs.Success)
            {
                Record = current;
                IsDatabaseChanged = true;
                FormValidator.ChangeState(FormValidation.FormState.Ready);

                //Testinng
                Record = DBManager.Detail_Setting(Record.SettingID);
                FillData();

                if (!UpdateMode)
                {
                    if (FormLib.confirm("Bạn có muốn thêm mới nữa không?", "Thông báo"))
                    {
                        ButtonAdd();
                    }
                    else
                    {
                        this.Close();
                    }
                }

                txSettingName.Text = Record.SettingName.ToString();
            }
            else
            {
                Global.FormMessageType messageType = UpdateMode ? Global.FormMessageType.UpdateFail : Global.FormMessageType.AddFail;
                Global.FormMessage(messageType, new string[] { "Thông tin báo cáo BHXH", txMaxScore.Text }, null, (Global.DBErrorType)rs.Result);
            }
        }

        public static bool ReturnCellValue(System.Windows.Forms.DataGridView datagrid, int rows, int sothutu)
        {
            if (datagrid.Rows[rows].Cells[sothutu].Value == null)
            {
                return false;
            } else {
                if ((bool)datagrid.Rows[rows].Cells[sothutu].Value.Equals(true))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public virtual void UpdateFormAction()
        {
            btn_dispose.Visible = Action.DisposeRecord;
            btn_save.Visible = Action.EditRecord || Action.AddRecord;
            btn_add.Visible = Action.AddRecord;
            btn_copy.Visible = false;

            //depend on UpdateMode 

            btn_save.Visible = Action.EditRecord || Action.EditRecordOwner || Action.AddRecord;
            btn_add.Visible = Action.AddRecord;

            //depend on UpdateMode 
            if (Action.EditRecord == true) //EditRecord == true -> free to edit any record
                btn_update.Visible = UpdateMode;
            else if (Action.EditRecordOwner == true) //EditRecordOwner == true -> if NguoiTao == username -> allow to edit
                btn_update.Visible = UpdateMode;

            if (Action.ConfirmRecord == true) //ConfirmRecord == true -> free to confirm any record
                btn_confirm.Visible = Record.Status == "A";
            else if (Action.DisposeRecordOwner == true) //DisposeRecordOwner == true -> if NguoiTao == username -> allow to dispose
                btn_confirm.Visible = Record.Status == "A";

            if (Action.DisposeRecord == true) //DisposeRecord == true -> free to dispose any record
                btn_dispose.Visible = UpdateMode && Record.Status == "XN";
            else if (Action.DisposeRecordOwner == true) //DisposeRecordOwner == true -> if NguoiTao == username -> allow to dispose
                btn_dispose.Visible = UpdateMode && Record.Status == "XN";

            //btn_confirm.Visible = Action.ConfirmRecord && Record.TinhTrang == "M";
            btn_confirm.Visible = Record.Status == "M";

            //btn_dispose.Visible = Action.DisposeRecord && UpdateMode && Record.TinhTrang == "XN";
            btn_dispose.Visible = UpdateMode && Record.Status == "XN";

            btn_print.Visible = UpdateMode && Record.Status == "XN";

            //update shortcutkey for button
            Global.InitDetailFormButton(this, btn_add, btn_update, btn_confirm, btn_dispose, btn_cancel, btn_save, btn_print);
            btn_print.Text = "In báo cáo(F7)";
            btn_dispose.Text = "Hủy báo cáo(F4)";
        }

        public virtual void InitFormValidation()
        {
            FormValidator = new FormValidation(this);
            FormValidator.AddHandleContainer(flp_container);
            FormValidator.InitNavigatorForm(btn_add, btn_update, btn_dispose, btn_save, btn_cancel, btn_confirm, btn_print);
            FormValidator.FormStateChanged += new FormValidation.FormStateChangeEvent(FormStateChanged);

            //init validation here
            FormValidator.ValidateText(txMaxScore, true,1, -1);
            //FormValidator.ValidateNumber(txDelayTime, true, 1, -1, "Không thể không có thời gian");

            //Global.InitDetailFormButton(this, btn_add, btn_update, btn_confirm, btn_dispose, btn_cancel, btn_save, btn_print);
            
            //txNgayTao.Enabled = false;
            //FormValidator.AddHandleControlExceptLock(txNgayTao);
            //FormValidator.AddHandleControlExceptLock(txPassword);
            //FormValidator.AddHandleControlExceptLock(NgayCapNhat);

            this.KeyDown += delegate(object sender, KeyEventArgs e)
            {
                switch (e.KeyCode)
                {
                    case Keys.Enter:
                        if (inDGV)
                        {
                            WindowLib.PressKey(Keys.Tab);
                        }
                        break;
                }
            };
        }

        public virtual void FormStateChanged(FormValidation.FormState state)
        {
            switch (state)
            {
                default:
                case FormValidation.FormState.Ready:
                    this.Text = FormTitle;
                    break;
                case FormValidation.FormState.CreateNew:
                    this.Text = FormTitle + " - Thêm mới";
                    break;
                case FormValidation.FormState.UpdateCurrent:
                    this.Text = FormTitle + " - Cập nhật";
                    break;
            }
        }

        public virtual void ViewDetail()
        {

            if (UpdateMode)
            {
                Setting result = DBManager.Detail_Setting(ID);
                Record = (Setting)result;
                FillData();

                lbLyDoHuy.Visible = lbNgayHuy.Visible = lbNguoiHuy.Visible = false;
                gbx_cotainer.Height = 180;
                //if (Record.Status != "H")
                //{
                //    lbLyDoHuy.Visible = lbNgayHuy.Visible = lbNguoiHuy.Visible = false;
                //    gbx_cotainer.Height = 144;
                //}
                //else
                //{
                //    lbLyDoHuy.Visible = lbNgayHuy.Visible = lbNguoiHuy.Visible = true;
                //    gbx_cotainer.Height = 210;
                //}
            }
            else
            {
                ButtonAdd();
            }
        }

        public virtual void FillData()
        {
            if (Record == null) return;

            if (NumberLib.getInt(Record.SettingID) == 0) return;

            txSettingName.Text = Global.GetString(Record.SettingName);
            txMaxScore.Text = Global.GetString(Record.MaxScore);
            txDelayTime.Text = Global.GetString(Record.DelayTime);

            TinhTrang.SelectedValue = Record.Status;
        }

        public virtual void ButtonPrint() 
        {
            //List<ReportData_ToaThuoc> source = new List<ReportData_ToaThuoc>();

            //using (var a = new Report_HanhChanh_BaoCaoBHXH_01A_TBH(Record.BaoCaoBHXH_ID)
            //{
            //    NgayGioIn = Global.GetServerDateTime().ToGioNgayString(),
            //    TenNguoiLap = UserAccount.Instance.TenNhanVien,
            //    ThoiGianBaoCao = Global.GetServerDateTime().ToGioNgayString(),
            //    TenGiamDoc = Configuration.Instance.TenGiamDoc,
            //    TenKeToanTruong = Configuration.Instance.TenKeToanTruong,
            //})
            //{
            //    a.ShowDialog();
            //}
        }
        #endregion

        #region Interface Support
        public void ThayDoiKichThuoc()
        {
            String tinhtranghientai = Global.GetString(TinhTrang.SelectedValue);
            if (tinhtranghientai == "H")
            {
                gbx_cotainer.Size = new Size(768, 120);
                //AddNhanVien.Location = new Point(12, 234);
            }
            else
            {
                gbx_cotainer.Size = new Size(768, 120);
                //AddNhanVien.Location = new Point(15, 161);
            }
        }
        #endregion

        #region Additon Func
        private void btn_add_VisibleChanged(object sender, EventArgs e)
        {
            btn_copy.Visible = btn_add.Visible;
        }

        private void btn_add_EnabledChanged(object sender, EventArgs e)
        {
            btn_copy.Enabled = btn_add.Enabled;
        }

        public virtual void FillCopyData(int IDCopy)
        {
            this.IDNhanDoi = IDCopy;

            NhanDoi = true;
        }

        private void GiaTriLuong_Leave(object sender, EventArgs e)
        {
            txMaxScore.Text = Global.FormatMoney(txMaxScore.Text);
        }

        private void TinhTrang_SelectedIndexChanged(object sender, EventArgs e)
        {
            ThayDoiKichThuoc();
        }
        #endregion
    }
}



